<?php
namespace app\mobile\controller;

use app\model\Record; 
use app\model\Fee; 
use app\model\Comm; 
use app\model\Theme; 
use app\model\Worker; 
use app\model\Order; 

class Sharehb extends Base
{
    public function Sharehb()
    {
global $_G, $_P;
$system    = $_G['system'];
$fans = $this->checkuser();
$op        = !empty($_P['op']) ? $_P['op'] : 'display';
$themeid = intval($_P['themeid']);
$theme = Theme::getThemeById($themeid);
$config = Theme::getConfig($themeid);
$fuid = $_G['member']['uid'];

$GLat= $_P['GLat'];
$GLng= $_P['GLng'];

if ($config['locationtype']==1 && (empty($GLat) || empty($GLng))){
	$result['errcode'] = 5;
	$result['msg'] = '没有获得地理位置信息，请打开手机gps，再刷新试试！';
	return_msg($result, '', 'ajax');
}

$workerid = intval($_P['wid']);
$theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);

// $randomfee = floatval(mt_rand($config['comm41']*100,$config['comm42']*100)/100);
//新版概率随机
$first = intval($config['comm43']);
$second= $first + intval($config['comm43_2']);
$gailv = mt_rand(0,99);
if ($first==0 || $first==100 || $gailv < $first ) {
    $randomfee = floatval(mt_rand($config['comm41']*100,$config['comm42']*100)/100);
}elseif ($gailv < $second && $config['comm42_2']!=0 ) {
    $randomfee = floatval(mt_rand($config['comm41_2']*100,$config['comm42_2']*100)/100);
}elseif ($config['comm42_3']!=0 ) {
    $randomfee = floatval(mt_rand($config['comm41_3']*100,$config['comm42_3']*100)/100);
}else{
    $randomfee = floatval(mt_rand($config['comm41']*100,$config['comm42']*100)/100);
}

$ClientIp = Comm::getClientIp();

$data = array(
	'uniacid'    => $_G['mpid'],
	'themeid'    => $themeid,
	'type'       => 4,
	'uid'     => $fuid,
	'openid'     => $_G['openid'],
	'addtime'    => TIMESTAMP,
	'fee'        => $randomfee,
	'ip'    => $ClientIp,
	'status'     =>0,
);

if (empty($theyworker)) {
	$workerid=0;
}elseif($theyworker['comm4status']>1){
	$workerid=0;
}elseif ($config['comm4typeyg']>0){
	$liulan = 0;
	$chengjiao = 0;
	switch ($config['comm4typeyg']) {
		case '1':
			$liulan = 30;
			break;
		case '2':
			$liulan = 40;
			break;
		case '3':
			$liulan = 50;
			break;
		case '4':
			$liulan = 60;
			break;
		case '5':
			$liulan = 70;
			break;
		case '6':
			$chengjiao = 5;
			break;
		case '7':
			$chengjiao = 10;
			break;
		case '8':
			$chengjiao = 15;
			break;
		case '9':
			$chengjiao = 20;
			break;
		case '10':
			$chengjiao = 25;
			break;
		case '11':
			$chengjiao = 30;
			break;
		case '12':
			$chengjiao = 40;
			break;
		case '13':
			$chengjiao = 50;
			break;
	}
	if ($config['forward']>500){
		if ($liulan>0) {
			if ($theyworker['forward']/$theyworker['scansum']*100 > $liulan){
				db_query("UPDATE ".tablename(t_worker)." SET comm4status = '2' WHERE uid ='{$workerid}'" );
				$workerid = 0;
			}
		}elseif ($chengjiao>0) {
			$cjtotal = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
					WHERE status > 0 and workerid = '{$workerid}' and themeid = '{$themeid}' " );
			if ($theyworker['forward'] / $cjtotal > $chengjiao){
				db_query("UPDATE ".tablename(t_worker)." SET comm4status = '2' WHERE uid ='{$workerid}'" );
				$workerid = 0;
			}
		}
	}

}
if (empty($workerid)) {
	$data['msg']='没有员工信息，不可领红包';
	$data['status']='9';
	$insertid = db_insert(t_commshare, $data);

	$result = array(
		"status"=>5,
		"msg"=>'感谢支持!',
	);
	return_msg($result, '', 'ajax');
}


if($op == 'comm' && $config['iscomm']==1 && $config['comm41'] > 0 && $system['fenxiao04'] ==1){

	$begintime1 = $theme['begintime'];
	$endime1 = $theme['endtime'];
	if($begintime1 > TIMESTAMP){
		$result['errcode'] = 1;
		$result['msg'] = '活动尚未开始，敬请期待~';
		return_msg($result, '', 'ajax');
	}
	if($endime1 < TIMESTAMP ||  $theme['status'] != 1){
		$result['errcode'] = 1;
		$result['msg'] = '活动已经结束啦，感谢您的支持';
		return_msg($result, '', 'ajax');
	}


	//失败的提示
	$result['errcode'] = 1;
    $result['msg'] = '感谢支持!';



	//在服务器别的软件领过的不可以领
	if ($config['comm4dashuju']==0){
		$status= Comm::gethistorycomm($themeid);
		if ($status['error']==1){
			$data['msg']=$status['msg'];
			$data['status']='8';
			$insertid = db_insert(t_commshare, $data);
	        return_msg($result, '', 'ajax');
	    }
	}
	
	// 1点-6点之前不发放
	if (date("H")<6 and date("H")>0) {
		$data['msg']='1点-6点之前不发放';
		$data['status']='10';
		$insertid = db_insert(t_commshare, $data);
		$result['errcode'] = 1;
        $result['msg'] = '感谢支持!';
        return_msg($result, '', 'ajax');
	}

	//员工是否有红包
	if ($config['comm4worker']==1){
		$myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
		if (!empty($myworker)){
			$data['msg']='员工裂变红包关闭';
			$data['status']='11';
			$insertid = db_insert(t_commshare, $data);
	        $result['errcode'] = 11;
	        $result['msg'] = '感谢支持!';
	        return_msg($result, '', 'ajax');
	    }
	}
	

	//判断付款的客户才有红包
	if ($config['comm4ispay']==1){
		$themyrecord = Record::getLastGroupByOpenId($_G['openid'],$themeid);
		if(empty($themyrecord)){
			$data['msg']='付款的客户才有红包';
			$data['status']='12';
			$insertid = db_insert(t_commshare, $data);
	        $result['errcode'] = 1;
	        $result['msg'] = '感谢支持!';
	        return_msg($result, '', 'ajax');
	    }
	}


	$fansinfo = db_find ( 'SELECT addtime,islock FROM ' . tablename ( t_fans ) . "
				WHERE uid ='{$fuid}'" );
	if($fansinfo['islock']==1){
		$data['msg']='用户已锁定，无法领裂变红包';
		$data['status']='12';
		$insertid = db_insert(t_commshare, $data);
        return_msg($result, '', 'ajax');
	}
	//10秒内刷新2次以上被锁定
	$sql = 'SELECT count(*) FROM ' . tablename ( t_commshare ) . "
				WHERE uid ='{$fuid}' and addtime > " ;
	$sql10 = TIMESTAMP - 10;
	$sharenum10 = db_fetchcolumn ($sql . $sql10);
	$sql120 = TIMESTAMP - 120;
	$sharenum120 = db_fetchcolumn ($sql . $sql120);
	$sql3600 = TIMESTAMP - 3600;
	$sharenum3600 = db_fetchcolumn ($sql . $sql3600);
	if ( $sharenum10 >= 3 || $sharenum120 >= 10 || $sharenum3600  >= 30) {
		db_query("UPDATE ".tablename(t_fans)." SET islock = '1' WHERE uid ='{$fuid}'" );
		
		$data['msg']='短时间内多次转发被封';
		$data['status']='2';
		$insertid = db_insert(t_commshare, $data);
        return_msg($result, '', 'ajax');
	}

	//打开链接30秒内分享朋友圈,自动锁定
	$addtime2=TIMESTAMP-$config['comm4sharetime'];
	if($fansinfo['addtime'] > $addtime2  || $fansinfo['islock']==1 || empty($fansinfo)){

		db_query("UPDATE ".tablename(t_fans)." SET islock = '1' WHERE uid ='{$fuid}'" );

		$data['msg']='链接打开'.$config['comm4sharetime'].'秒内转发被封';
		$data['status']='2';
		$insertid = db_insert(t_commshare, $data);
        return_msg($result, '', 'ajax');
	}

	//检测时间
	if (!empty($config['comm4time'])) {
		$comm4time= Comm::getCommshareTime($themeid,$fuid);
		if ($comm4time < $config['comm4time']){
			$data['msg']='离下次领取还有'.($config['comm4time']-$comm4time).'分钟';
			$data['status']='5';
			$insertid = db_insert(t_commshare, $data);
			$result['errcode'] = 5;
    		$result['msg'] = $data['msg'];
	        return_msg($result, '', 'ajax');
	    }
	}
	
	//检测3小时内成交数与发红包数是否达到要求
	if (!empty($config['comm4type']) || !empty($config['comm4typehb'])){
		$status= Comm::gethourslimit($themeid,$config['comm4type'],$config['comm4typehb']);
		if ($status['error']==1){
			$data['msg']=$status['msg'];
			$data['status']='8';
			$insertid = db_insert(t_commshare, $data);
	        return_msg($result, '', 'ajax');
	    }
	}

	//检测今日已领的个数
	$comm4daynum= Comm::getCommshareToday($themeid,$fuid);
	if ($comm4daynum >= $config['comm4daynum']){
		$data['msg']='每天只可领'.$config['comm4daynum'].'个红包';
		$data['status']='6';
		$insertid = db_insert(t_commshare, $data);
		$result['errcode'] = 5;
		$result['msg'] = $data['msg'];
        return_msg($result, '', 'ajax');
    }

    //检测已领的总个数
	$comm4sum= Comm::getCommshareAll($themeid,$fuid);
	if ($comm4sum >= $config['comm4sum']){
		$data['msg']='您总计可领'.$config['comm4sum'].'个红包';
		$data['status']='7';
		$insertid = db_insert(t_commshare, $data);
		$result['errcode'] = 5;
		$result['msg'] = $data['msg'];
        return_msg($result, '', 'ajax');
    }

	//检测每小时限额
	$Numhour= floatval(Comm::getCommshareNumHour($themeid));
	if ($Numhour>=floatval($config['comm4hour'])){
		$data['msg']='红包达小时上限';
		$data['status']='3';
		$insertid = db_insert(t_commshare, $data);
        return_msg($result, '', 'ajax');
    }

	//检测每天限额
	$NumDay= floatval(Comm::getCommshareNumDay($themeid));
	if ($NumDay>=floatval($config['comm4day'])){
		$data['msg']='今日红包已发完';
		$data['status']='3';
		$insertid = db_insert(t_commshare, $data);
        return_msg($result, '', 'ajax');
    }


	//检测同一IP
	if (!empty($config['comm4ip'])) {
		$NumIp= floatval(Comm::getCommshareNumIp($themeid,$ClientIp));
		if ($NumIp>=floatval($config['comm4ip'])){
			$data['msg']='同一网络到上限';
			$data['status']='4';
			$insertid = db_insert(t_commshare, $data);
	        return_msg($result, '', 'ajax');
	    }
	}

	if ($config['locationtype']==1) {
		$City= Comm::getCityDW($GLat, $GLng,$config['comm4city']);
	}else{
		$City= Comm::getCity($system,$ClientIp,$config['comm4city']);
	}

	$data['city']=$City['city'];
	
	//根据IP检测地区
	if (!empty($config['comm4city']) && $City['status']==0){
		$data['msg']='不在活动地区';
		$data['status']='2';
		$insertid = db_insert(t_commshare, $data);
        return_msg($result, '', 'ajax');
	}

    $insertid = db_insert(t_commshare, $data);


	$weizhifulist = db_find ( 'SELECT city,fee FROM ' . tablename ( t_commshare ) . "
				WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fuid}'" );
	$weizhifu = $weizhifulist['fee'];
	if ($weizhifu>=0.3 || ($config['comm4autored']==3 && $weizhifu>0)){


		$ordersn = getMillisecond();
		$data = array(
			'uniacid'    => $_G['mpid'],
			'themeid'    => $themeid,
			'recordid'   => '',
			'ordersn'    => $ordersn,
			'type'       => 4,
			'uid'     => $fuid,
			'openid'     => $_G['openid'],
			'addtime'    => TIMESTAMP,
			'fee'        => $weizhifu,
			'ip'    => $ClientIp,
			'city'    => $weizhifulist['city'],
			'fromuid'    => 0,
			'status'     =>0,
		);
		$data2= $data;
	    $data2['software'] = MODULE_NAME;
	    $insertid = db_insert('2019comm_list', $data2);
	
        //1分钟内只能收到一个红包
        if (empty($weizhifulist['addtime'])) {
        	$addtime =  TIMESTAMP - 60;
        }else{
        	$addtime =  $weizhifulist['addtime'] - 60;
        }
        $p = array(':themeid' => $data['themeid'],':uid' => $data['uid'],':type' => $data['type'],':addtime' => $addtime );        
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and uid= :uid and type= :type and addtime > :addtime" ;
        $commrow = db_find($sql,$p);
        if (!empty($commrow)){
			$data['msg']='1分钟内只能收到一个红包';
			// $insertid = db_insert(t_comm, $data);
			db_query("UPDATE ".tablename(t_commshare)." SET status = 5, msg = '操作频繁：1分钟内只能收到一个红包'
				WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fuid}'" );
			$result['errcode'] = 5;
			$result['msg'] = '感谢支持';

	        return_msg($result, '', 'ajax');
		}else{			
			//将所有未支付记录更新为正常
			db_query("UPDATE ".tablename(t_commshare)." SET status = 1, sendtime = ".TIMESTAMP."
				WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fuid}'" );
		}
		

		if($system['autored']== 0 || $config['comm4autored']== 0 || ($config['comm4autored']== 2 && TIMESTAMP > $config['comm4autoredtime']) ){				
			$data['msg']='等待管理员发红包';
			$comm4tips = str_replace("#fee",$weizhifu,$config['comm4tips']);
			$result['errcode'] = 5;
			$result['msg'] = $comm4tips;
			$insertid = db_insert(t_comm, $data);
	        return_msg($result, '', 'ajax');
	    }
	    if($config['comm4autored']== 3){				
			$data['msg']='待客户提现';

			$pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
			$totalfail = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename (t_comm) . ' as m 
			            WHERE m.themeid = :themeid and status=0 and type<>99 and m.openid = :openid',$pm);
			$totalsuccess = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename (t_comm) . ' as m 
		            WHERE m.themeid = :themeid and (status=1 or status=0 and type=99) and m.openid = :openid',$pm);

			$chae = $config['hbtixian']-$totalfail-$weizhifu;
			if ($chae<0 || ($totalsuccess>0 && $config['hbtixianmode'] == 0)) {
				$comm4tips = "恭喜您获得红包" . $weizhifu . "元，可在【我的红包】中提现";
			}else{
				$comm4tips = "恭喜您获得红包" . $weizhifu . "元，再有".$chae."元就可提现了";
			}
			$result['errcode'] = 5;
			$result['msg'] = $comm4tips;
			$insertid = db_insert(t_comm, $data);
	        return_msg($result, '', 'ajax');
	    }

	    $totalpayfee = Order::getRealByThemeIdcomm4($themeid) + $theme['chongzhi'];
		if ($totalpayfee<0){
			$data['msg']='您的余额不足,请联系客服进行充值';
			$insertid = db_insert(t_comm, $data);
	        return_msg($result, '', 'ajax');
		}

		$insertid = db_insert(t_comm, $data);

	    $row = Comm::getCommZhuanfa($data);
	    $r = array();
	    if(!empty($row) && $row['fee']>=0.3){
	        // $cachekey = 'comm'.$_G['mpid'].MODULE_NAME.$row['id'];
	        // $settings = cache_load($cachekey);
	        // if(empty($settings)){
	            $settings = "commid:".$row['id'];
	            // cache_write($cachekey, $settings);
	            $r = Fee::commRecord($row,$system);
	            if ($r[0]==0){
				    $result['errcode'] = 2;
				    $result['fee'] = $randomfee;
				    $result['fee2'] =$weizhifu;
				    return_msg($result, '', 'ajax');
	            }
	        // }
	    }else{
	        $result['errcode'] = 1;
	        $result['msg'] = '感谢支持!';
	        return_msg($result, '', 'ajax');
	    }
	}else{
	    $result['errcode'] = 3;
	    $result['fee'] = $randomfee;
	    return_msg($result, '', 'ajax');
	}
}



if($op == 'check'){
	if($system['autored']== 0){
        $result['errcode'] = 1;
        $result['msg'] = 'autored is clsesd';
        return_msg($result, '', 'ajax');
    }
    $list = db_select( "SELECT * FROM " . tablename (t_comm) . " WHERE status = 0 order by id desc");
    foreach ($list as $index =>$row){
        $r = Fee::commRecord($row,$system);
    }
    $result['errcode'] = 0;
    $result['list'] = $list;
    return_msg($result, '', 'ajax');
}


}
}